const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require('path');
const dataController = require('../controllers/dataController');
const { pool } = require('../models/db');
require('dotenv').config();

const uploadDir = path.join(__dirname, '../../', process.env.UPLOAD_DIR || 'uploads');
if (!require('fs').existsSync(uploadDir)) {
  require('fs').mkdirSync(uploadDir, { recursive: true });
}

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
    const ext = path.extname(file.originalname);
    const safeFilename = encodeURIComponent(file.fieldname) + '-' + uniqueSuffix + ext;
    cb(null, safeFilename);
  }
});

const fileFilter = (req, file, cb) => {
  const allowedImageTypes = ['image/jpeg', 'image/png', 'image/jpg'];
  const allowedExcelTypes = [
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'application/vnd.ms-excel',
    'application/msexcel',
    'application/x-excel'
  ];
  
  if (file.fieldname === 'excelFile') {
    allowedExcelTypes.includes(file.mimetype) ? cb(null, true) : cb(new Error('只允许上传.xlsx和.xls格式的Excel文件'), false);
  } else {
    allowedImageTypes.includes(file.mimetype) ? cb(null, true) : cb(new Error('只允许上传JPG和PNG格式的图片'), false);
  }
};

const upload = multer({ 
  storage: storage,
  fileFilter: fileFilter,
  limits: { fileSize: 5 * 1024 * 1024 }
});

router.use((err, req, res, next) => {
  if (err instanceof multer.MulterError) {
    return res.status(400).json({ error: `文件上传错误: ${err.message}` });
  } else if (err) {
    return res.status(400).json({ error: err.message });
  }
  next();
});

// 厅名管理
router.get('/halls', dataController.getHalls);
router.post('/halls', express.json(), async (req, res) => {
  console.log('req.body', req.body);
  try {
    const { hallName } = req.body;
    if (!hallName) {
      return res.status(400).json({ error: '厅名不能为空' });
    }
    
    const [result] = await pool.query(
      'INSERT INTO halls (hall_name) VALUES (?)', 
      [hallName]
    );
    
    res.status(201).json({ message: '厅名添加成功', hallId: result.insertId });
  } catch (error) {
    console.log('error', error);
    if (error.code === 'ER_DUP_ENTRY') {
      return res.status(400).json({ error: '该厅名已存在' });
    }
    res.status(500).json({ error: '添加厅名失败' });
  }
});

router.delete('/halls/:id', async (req, res) => {
  try {
    const id = decodeURIComponent(req.params.id);
    const [result] = await pool.query(
      'DELETE FROM halls WHERE id = ?', 
      [id]
    );
    console.log(id,result)
    if (result.affectedRows === 0) {
      return res.status(404).json({ error: '厅名不存在' });
    }
    
    res.status(200).json({ message: '厅名删除成功' });
  } catch (error) {
    res.status(500).json({ error: '删除厅名失败' });
  }
});

// 数据操作
router.get('/query', dataController.queryData);
router.post('/upload', upload.fields([
  { name: 'dataScreenshot', maxCount: 1 },
  { name: 'headDataScreenshot', maxCount: 1 }
]), dataController.uploadSingleData);
router.post('/upload-excel', upload.single('excelFile'), dataController.uploadExcelData);
router.delete('/:id', dataController.deleteData);

module.exports = router;